from django.utils.decorators import method_decorator
from rest_framework.viewsets import GenericViewSet
from djcelery import models
from rest_framework.response import Response
from FasterRunner import pagination
from fastrunner import serializers
from fastrunner.utils import response
from fastrunner.utils.decorator import request_log
from fastrunner.utils.task import Task
import json
from django.core.exceptions import ObjectDoesNotExist
from fastrunner import models as models2
class ScheduleView(GenericViewSet):
    """
    定时任务增删改查
    """
    queryset = models.PeriodicTask.objects
    serializer_class = serializers.PeriodicTaskSerializer
    pagination_class = pagination.MyPageNumberPagination

    @method_decorator(request_log(level='DEBUG'))
    def list(self, request):
        """
        查询项目信息
        """
        project = request.query_params.get("project")
        schedule = self.get_queryset().filter(description=project).order_by('-date_changed')
        page_schedule = self.paginate_queryset(schedule)
        serializer = self.get_serializer(page_schedule, many=True)
        print("------------------ 55 --------------------")
        print(self.get_paginated_response(serializer.data))
        return self.get_paginated_response(serializer.data)

    @method_decorator(request_log(level='INFO'))
    def add(self, request):
        """新增定时任务{
            name: str
            corntab: str
            switch: bool
            data: [int,int]
            strategy: str
            receiver: str
            copy: str
            project: int
        }
        """
        task = Task(**request.data)
        resp = task.add_task()
        return Response(resp)


    @method_decorator(request_log(level='INFO'))
    def update(self, request):
        """
        编辑项目
        """
        print("**编辑定时任务")
        project = request.data["project"]

        try:
            project2 = models2.Project.objects.get(id=project)

        except (KeyError, ObjectDoesNotExist):
            return Response(response.SYSTEM_ERROR)


        project2.name = request.data['name']
        project2.save()
        print("项目名称保存完成！")
        print("-------")
        print("这是一堆什么东西？", request.data)

        task2 = Task(**request.data)
        resp = task2.update_task()
        print("**5: ", resp)
        print("**6: ", request.data)

        return Response(response.PROJECT_UPDATE_SUCCESS)



    @method_decorator(request_log(level='INFO'))
    def delete(self, request, **kwargs):
        """删除任务
        """
        print("**删除")
        task = models.PeriodicTask.objects.get(id=kwargs["pk"])
        task.enabled = False
        task.delete()
        schedule = models.CrontabSchedule.objects.get(id=task.crontab_id)
        schedule.delete()
        return Response(response.TASK_DEL_SUCCESS)